package com.ruyuan.seckilling.purchase.async.listener;

import com.ruyuan.seckilling.common.CacheKey;
import com.ruyuan.seckilling.purchase.async.BasePurchaseListener;
import com.ruyuan.seckilling.purchase.async.PurchaseContext;
import com.ruyuan.seckilling.purchase.async.event.Step1CheckProduct;
import com.ruyuan.seckilling.purchase.async.event.Step2CheckUser;
import com.ruyuan.starter.async.anno.Channel;
import com.ruyuan.starter.async.event.BaseEvent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * 校验用户是否已经抢购了商品
 *
 * @author zhonghuashishan
 */
@Slf4j
@Component
@Channel("step1")
public class Step1Listener extends BasePurchaseListener<Step1CheckProduct> {

    @Override
    public boolean accept(BaseEvent event) {
        return event instanceof Step1CheckProduct;
    }

    @Override
    protected void doThisStep(Step1CheckProduct event, PurchaseContext purchaseContext) {
        executorService.execute("step1", () -> {
            Long activity = purchaseContext.getActivityId();
            Long userId = purchaseContext.getUserId();
            Long skuId = purchaseContext.getSkuId();
            String key = CacheKey.buildCheckProductKey(activity, userId, skuId);
            if (!cacheSupport.exists(key)) {
                log.info("校验用户是否已经抢购了商品，用户还未抢购过");
                // 用户还没有抢购成功过这个商品，进入第二步校验用户的抢购次数
                bossEventBus.publish("step2", new Step2CheckUser(), purchaseContext);
                return;
            }
            response(purchaseContext.getAsyncContext(), false, "您已经抢购过该商品了");
        });
    }
}
